<template>
  <dialog-View :isShow="_isOpen" :title="title" :width="500">
    <form-View
      :formList="formList"
      :rules="rules"
      :position="'left'"
      :editItem="orderDetail"
      @update="handelSubmit"
      @back="handelCancel"
    ></form-View>
  </dialog-View>
</template>
<script setup>
import dialogView from "./dialogView.vue";
import formView from "./formView.vue";
import { updateOrderInfo } from "@/apis/order";
import { computed } from "vue";
import china from "@/utils/china.json";

const converAddress = arr => {
  arr = arr.map(item => {
    if (item.children) item.children = converAddress(item.children);
    return {
      ...item,
      label: item.name,
      value: item.cityCode
    };
  });
  return arr;
};

const formList = [
  { label: "收货人", model: "receivingName", type: "input", max: 10 },
  { label: "手机", model: "receivingMobile", type: "input", max: 11 },
  { label: "收货地址", model: "receivingAreaIds", type: "cascader", options: converAddress(china), max: 10 },
  { label: "详细地址", model: "receivingAddress", type: "input", max: 100 }
];
const rules = {
  receivingName: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { min: 1, max: 200, message: "请输入名称", trigger: "blur" }
  ],
  receivingMobile: [
    { required: true, message: "请输入电话", trigger: "blur" },
    { min: 1, max: 200, message: "请输入电话", trigger: "blur" }
  ],
  receivingAreaIds: [
    {
      required: true,
      message: "请选择地址",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (value.length === 0) {
          return callback(new Error("请选择一个地址"));
        }
        return callback();
      }
    }
  ],
  receivingAddress: [
    { required: true, message: "请输入详细地址", trigger: "blur" },
    { min: 1, max: 300, message: "请输入详细地址", trigger: "blur" }
  ]
};

const props = defineProps({
  title: { type: String, default: "添加备注信息" },
  modelValue: { type: Boolean, default: false },
  orderDetail: { type: Object, default: () => ({}) },
  // 是否调用接口
  isPostApi: { type: Boolean, default: true }
});

const emit = defineEmits(["update:modelValue", "success"]);

const _isOpen = computed({
  get: () => props.modelValue,
  set: newVal => emit("update:modelValue", newVal)
});

const handelSubmit = async ({ receivingName, receivingMobile, receivingAddress, receivingAreaIds }, address) => {
  let postData = {
    orderId: props.orderDetail.orderId,
    receivingName,
    receivingMobile,
    receivingAreaIds: receivingAreaIds.join(),
    receivingAddress,
    receivingAreaDetail: address
  };
  if (props.isPostApi) {
    await updateOrderInfo(postData);
    _isOpen.value = false;
    emit("success", "修改地址成功");
  } else {
    _isOpen.value = false;
    emit("success", "修改地址成功", postData);
  }
};

const handelCancel = () => {
  _isOpen.value = false;
};
</script>
